<template>
  <div class="user">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        v-model="form"
        :page="page"
        :table-loading="listLoading"
        :before-open="handleOpenBefore"
        :data="list"
        @on-load="getList"
        @search-change="handleFilter"
        @refresh-change="handleRefreshChange"
        @row-update="update"
        @search-reset="searchReset"
        @row-save="create">
        <template
          slot="username"
          slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
        <template
          slot="role"
          slot-scope="scope">
          <span
            v-for="(role,index) in scope.row.roleList"
            :key="index">
            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <template
          slot="deptId"
          slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
        <template
          slot="lockFlag"
          slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <template
          slot="roleForm"
          slot-scope="scope">
          <avue-select
            v-model="role"
            :dic="rolesOptions"
            :props="roleProps"
            placeholder="请选择角色"/>
        </template>
        <!-- <template slot='menuLeft'>
            <el-upload
                  class="upload-inline"
                  action=""
                  :show-file-list="false"
                  accept=".xls,.xlsx"
                  :http-request="handleImport"
                  >
                  <el-button type="primary" size="small">导入</el-button>
          </el-upload>
        </template> -->
        <template slot="manageStationsForm" slot-scope="scope">
          <dynamic-crud
            title="管理线路与站点"
            :data="form.manageStations"
            :option="stationsOption"
            :disabled="window.boxType == 'view'"
          >
          </dynamic-crud>
        </template>
      </avue-crud>
    </basic-container>
  </div>

</template>

<script>
    import {addObj, delObj, fetchList, putObj,saveBatch} from '@/api/admin/user'
    import {deptRoleList} from '@/api/admin/role'
    import {tableOption} from '@/const/crud/admin/userACC'
    import {mapGetters} from 'vuex'

    export default {
        name: 'SysUserLC',
        data() {
            return {
                window: window,
                searchForm: {},
                option: tableOption,
                roleProps: {
                    label: 'roleName',
                    value: 'roleId'
                },
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false// 是否倒序
                },
                list: [],
                listLoading: true,
                role: [],
                form: {},
                rolesOptions: [],
                stationsOption: {
                  column: [
                    {
                      label: "线路",
                      prop: "line",
                      type: "select",
                      cascaderItem: ["station"],
                      props: {
                        label: "name",
                        value: "code"
                      },
                      dicUrl: "/support/swparamline/dict",
                      cell: true,
                      rules: [{ required: true, message: "请选择线路", trigger: "blur" }]
                    },
                    {
                      label: "站点",
                      prop: "station",
                      type: "select",
                      dicFlag: false,
                      props: {
                        label: "name",
                        value: "code"
                      },
                      dicUrl: "/support/swparamstation/dict/{{key}}",
                      cell: true
                    }
                  ]
                }
            }
        },
        computed: {
            ...mapGetters(['permissions'])
        },
        watch: {
            role() {
                this.form.role = this.role ? [this.role] : []
            },
            "form.belongToLine"(val) {
              this.findObject(this.option.column, "lineCode").display = !val;
              this.findObject(this.option.column, "stationCode").display = !val;

              //如果是非线网人员，也可以设置管辖线路
              //this.findObject(this.option.column, "isManageStation").display = val;
              if (val) {
                // 线网人员，线路,车站和设备操作号为空
                this.form.lineCode = null;
                this.form.stationCode = null;
              } else {
                if (this.validatenull(this.form.manageStations)) {
                  this.form.isManageStation = false;
                  this.form.managementLineStation = null;
                }else{
                  this.form.isManageStation = true;
                }
              }
            },
            "form.isManageStation"(val) {
              this.findObject(this.option.column, "manageStations").display = val;
            }
        },
        created() {
            this.sys_user_add = this.permissions['sys_user_add']
            this.sys_user_edit = this.permissions['sys_user_edit']
            this.sys_user_del = this.permissions['sys_user_del']
        },
        methods: {
            getList(page, params) {
              this.listLoading = true;
              return fetchList(
                Object.assign(
                  {
                    current: page.currentPage,
                    size: page.pageSize
                  },
                  params,
                  this.searchForm
                )
              ).then(response => {
                let records = response.data.data.records;
                records.forEach(r => {
                  if (r.managementLineStation) {
                    r.isManageStation = true;
                    r.manageStations = JSON.parse(r.managementLineStation);
                    r.manageStations.forEach(s => {
                      s.$cellEdit = true;
                    });
                  } else {
                    r.isManageStation = false;
                    r.manageStations = [];
                  }
                });
                this.list = records;
                this.page.total = response.data.data.total;
                this.listLoading = false;
              });
            },
            handleFilter(param, done) {
                this.searchForm = param
                this.getList(this.page, param).then(() => {
                  done()
                })
            },
            handleImport(item){
              let file = item.file
              let param = new FormData()
              param.append('file',file)
              saveBatch(param).then(() => {
                this.$notify({
                  title: '成功',
                  message: '导入成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList(this.page)
              })
            },
            handleRefreshChange() {
                this.getList(this.page)
            },
            handleCreate() {
                this.$refs.crud.rowAdd()
            },
            handleOpenBefore(show, type) {
                window.boxType = type
                if (['edit', 'views'].includes(type)) {
                    for (var i = 0; i < this.form.roleList.length; i++) {
                        this.role = this.form.roleList[i].roleId
                        this.form.role = [this.role]
                    }
                } else if (type === 'add') {
                    this.role = null
                }
                deptRoleList().then(response => {
                    this.rolesOptions = response.data.data;
                    const roles =  this.rolesOptions.filter(w => w.roleCode== 'SYSHZB' || w.roleCode=='INCOMESPONSOR' || w.roleCode=='TICKETDIRECTOR');
                    this.rolesOptions = roles;
                })
                show()
            },
            handleUpdate(row, index) {
                this.$refs.crud.rowEdit(row, index)
                this.form.password = undefined
            },
            create(row, done, loading) {
              // if (this.form.phone.indexOf('*') > 0) {
              //     this.form.phone = undefined
              // }
              if (this.validatenull(this.form.manageStations)) {
                this.form.managementLineStation = null;
              } else {
                let lineStations = this.form.manageStations.map(r => {
                  return {
                    line: r.line,
                    station: r.station
                  };
                });
                this.form.managementLineStation = JSON.stringify(lineStations);
              }
              delete this.form.manageStations;
              delete this.form.dates1;
              addObj(this.form).then(() => {
                  this.getList(this.page)
                  done()
                  this.$notify({
                      title: '成功',
                      message: '创建成功',
                      type: 'success',
                      duration: 2000
                  })
              }).catch(() => {
                  loading()
              })
            },
            update(row, index, done, loading) {
              // if (this.form.phone && this.form.phone.indexOf('*') > 0) {
              //     this.form.phone = undefined
              // }
              if (this.validatenull(this.form.manageStations)) {
                this.form.managementLineStation = null;
              } else {
                let lineStations = this.form.manageStations.map(r => {
                  return {
                    line: r.line,
                    station: r.station
                  };
                });
                this.form.managementLineStation = JSON.stringify(lineStations);
              }
              delete this.form.manageStations;
              delete this.form.dates1;
              putObj(this.form).then(() => {
                  this.getList(this.page)
                  done()
                  this.$notify({
                      title: '成功',
                      message: '修改成功',
                      type: 'success',
                      duration: 2000
                  })
              }).catch(() => {
                  loading()
            })
            },
            searchReset(form){
              for(let key of Object.keys(form)){
                if(this.validatenull(form[key])){
                  delete form[key]
                }
              }
              this.searchForm = form
              this.page.currentPage = 1
              this.getList(this.page);
            },
            deletes(row, index) {
                this.$confirm(
                    '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    delObj(row.userId)
                        .then(() => {
                            this.list.splice(index, 1)
                            this.$notify({
                                title: '成功',
                                message: '删除成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                        .cache(() => {
                            this.$notify({
                                title: '失败',
                                message: '删除失败',
                                type: 'error',
                                duration: 2000
                            })
                        })
                })
            }
        }
    }
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>
